package jmu.edu.yjc.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import jmu.edu.yjc.Utils.RedisCache;
import jmu.edu.yjc.annotation.SystemLog;
import jmu.edu.yjc.domain.ResponseResult;
import jmu.edu.yjc.domain.entity.User;
import jmu.edu.yjc.enums.AppHttpCodeEnum;
import jmu.edu.yjc.exception.SystemException;
import jmu.edu.yjc.service.LoginService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class LoginController {
    @Resource
    private LoginService loginService;
    @Resource
    private RedisCache redisCache;
    @PostMapping("/login")
    @SystemLog(businessName = "用户登录")
    @ApiOperation(value = "用户登录")
    public ResponseResult userLogin(@RequestBody String json, HttpServletRequest request){
        // fastjson转成json对象
        JSONObject jsonObject = JSON.parseObject(json);
        // 在转成不同的实体类
        String userName = jsonObject.getObject("username", String.class);
        String password = jsonObject.getObject("password", String.class);
        if(!StringUtils.hasText(userName)){
            return ResponseResult.errorResult(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        String code = jsonObject.getObject("code",String.class);
        //不区分大小写
        code = code.toUpperCase();
        HttpSession session = request.getSession();
        String sessionCode = null;
        try {
            sessionCode = redisCache.getCacheObject(session.getId());
        }catch (Exception ignored){

        }
        if(sessionCode==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.CODE_ERROR_EXPIRE);
        }else {
//        System.out.println(sessionCode);
            if (!sessionCode.equals(code)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.CODE_ERROR);
            }
        }
        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        return loginService.userLogin(user);
    }
    @PostMapping("/logout")
    @ApiOperation(value = "用户注销")
    public ResponseResult userLogout(){
        return loginService.userLogout();
    }
}
